//
//  ViewController.m
//  OCUI
//
//  Created by login on 15-6-23.
//
//

#import "DestinationViewController.h"
#import "Header.h"
#import "SBJSON.h"
#import "ASIHTTPRequest.h"
#import "HttpClient.h"
#import "DataModal.h"
#import "CitiesTableViewCell.h"

@interface DestinationViewController ()<UITextFieldDelegate,ASIHTTPRequestDelegate,UITableViewDataSource,UITableViewDelegate>
{
    NSArray *_checkArray;
    UITextField *_inputCity;
    UITableView *_citiesTableView;
    NSDictionary *_cityDict;

}
@end

@implementation DestinationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController setNavigationBarHidden:YES];
    [self initUI];
}

#pragma mark - 初始化输入框
- (void)initUI
{
    
//    header
    
    UILabel *label = [[UILabel alloc]init];
    label.text = @"目的城市";
    label.backgroundColor = DEFAULTCOLOR;
    label.textColor = [UIColor whiteColor];
    [label setFont:[UIFont systemFontOfSize:25]];
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];
    
    UIButton *returnButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 32, 25,25)];
    [returnButton setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    [returnButton addTarget:self action:@selector(returnHomeViewController) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:returnButton];
    
    UIButton *homeButton = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-40, 30, 30, 30)];
    [homeButton setImage:[UIImage imageNamed:@"iconfont-home"] forState:UIControlStateNormal];
    [homeButton addTarget:self action:@selector(returnHomeViewController) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:homeButton];
    
    //输入框
//    _inputCity = [[UITextField alloc]initWithFrame:CGRectMake(40, HEIGHT/4, WIDTH/2, 35)];
    _inputCity = [[UITextField alloc]init];
    _inputCity.center = CGPointMake(self.view.center.x, self.view.center.y/3);
    _inputCity.placeholder = @"请输入简拼/全拼/汉字";
    _inputCity.backgroundColor = [UIColor clearColor];
    _inputCity.clearButtonMode = UITextFieldViewModeWhileEditing;
    _inputCity.delegate = self;
    [_inputCity setBorderStyle:UITextBorderStyleRoundedRect];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 28, 28)];
    imageView.image = [UIImage imageNamed:@"editinput"];
    _inputCity.leftView = imageView;
    _inputCity.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:_inputCity];
    
    
    //    注册监听 观察textField输入长度
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(downloadData) name:UITextFieldTextDidChangeNotification object:nil];

    UIButton *makeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    makeButton.layer.cornerRadius = 8.0;
    [makeButton setBackgroundColor:DEFAULTCOLOR];
    [makeButton setTitle:@"确定" forState:UIControlStateNormal];
    [makeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    makeButton.titleLabel.font = [UIFont systemFontOfSize:18];
    [makeButton addTarget:self action:@selector(downloadData) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:makeButton];
    
    
    _citiesTableView = [[UITableView alloc]init];
    _citiesTableView.dataSource = self;
    _citiesTableView.delegate = self;
    _citiesTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_citiesTableView];
    
//    souyin = [NSMutableArray array];
//    
//    for (char c='A'; c<'Z'; c++) {
//        
//        NSString *zimu = [NSString stringWithFormat:@"%c",c];
//        if (![zimu isEqualToString:@"I"]&&![zimu isEqualToString:@"O"]&&![zimu isEqualToString:@"U"]&&![zimu isEqualToString:@"V"]) {
//            [souyin addObject:[NSString stringWithFormat:@"%c",c]];
//        }
//    }
    
    
    [label setTranslatesAutoresizingMaskIntoConstraints:NO];
    [_inputCity setTranslatesAutoresizingMaskIntoConstraints:NO];
    [_citiesTableView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [makeButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    NSDictionary *dict = NSDictionaryOfVariableBindings(label,_inputCity,_citiesTableView,makeButton);
    NSDictionary *metrice = @{@"pad":@20,@"edge":@50,@"_inputCityWidth":@50,@"_inputCityWidthHeight":@35};
    
//    横向约束
    NSString *vf10 = @"|[label]|";
    NSString *vf11 = @"H:|-pad-[_inputCity(>=_inputCityWidth)]-5-[makeButton(==_inputCityWidth)]-pad-|";
    NSString *vf12 = @"|[_citiesTableView]|";
//    纵向约束
    NSString *vf20 = @"V:|-pad-[label(==50)]-pad-[_inputCity(==_inputCityWidthHeight)]-pad-[_citiesTableView]-|";
    NSString *vf21 = @"V:|-pad-[label(==50)]-pad-[makeButton(==_inputCityWidthHeight)]-pad-[_citiesTableView]-|";

    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:vf10 options:0 metrics:metrice views:dict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:vf11 options:0 metrics:metrice views:dict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:vf12 options:0 metrics:metrice views:dict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:vf20 options:0 metrics:metrice views:dict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:vf21 options:0 metrics:metrice views:dict]];


    
}

//- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
//{
//    if (tableView == self.searchDisplayController.searchResultsTableView) {
//        return nil;
//    }
//    return souyin;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
//{
//    NSLog(@"===%@  ===%ld",title,index);
//    
//    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index+4] atScrollPosition:UITableViewScrollPositionTop animated:YES];
//    
//    return index+4;
//    
//}

#pragma mark - 每当_inputCity.text的长度发生变化时 下载数据
- (void)downloadData
{
    NSString *string = [NSString stringWithFormat:@"%@%@",HOSTURL,CHECKCITIES];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_inputCity.text,@"word", nil];
    
    
    [HttpClient getRequestWithProgress:self.view and:string and:dic requestType:GET andResult:^(NSArray *mainArray) {
        
        [self performSelectorOnMainThread:@selector(updateUI:) withObject:mainArray waitUntilDone:YES];
        
    }];
    

}
#pragma mark - 收回键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - 查询数据并更新UITableView
- (void)updateUI:(NSArray *)array
{
    if (array.count == 0) {
        
    }
    _checkArray = [array copy];
    [_citiesTableView reloadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _checkArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"citiesCell1";
    CitiesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[CitiesTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    cell.cityFindName.text = _checkArray[indexPath.row][@"findname"];
    cell.cityQanPin.text = _checkArray[indexPath.row][@"find_quanpin"];
    
    return cell;
}
#pragma mark - UITabelViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _inputCity.text = _checkArray[indexPath.row][@"findname"];
    _cityDict = _checkArray[indexPath.row];
}
#pragma mark - 返回主视图
- (void)returnHomeViewController
{
    DataModal *modal = [DataModal defaultManager];
    modal.cityDic = [_cityDict copy];
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
